package com.design.elegant.pipeline.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author coderxdh
 * @date 2023/12/10 20:33
 */
@Slf4j
@Component
public class ThreadPoolManager {
    // 创建一个根据需要创建新线程的线程池，该线程池根据工作负载自动调整线程数量。该线程池使用ForkJoinPool来实现任务的分配和执行
    private final ExecutorService pipelineExecutorService = Executors.newWorkStealingPool();

    public ExecutorService getPipelineExecutorService() {
        log.info("getPipelineExecutorService");
        return pipelineExecutorService;
    }

    @PreDestroy
    public void shutdown() {
        log.info("pipelineExecutorService shutdown");
        pipelineExecutorService.shutdown();
        try {
            if (!pipelineExecutorService.awaitTermination(60, TimeUnit.SECONDS)) {
                log.info("Forcing shutdownNow of pipelineExecutorService as it didn't respond to shutdown");
                pipelineExecutorService.shutdownNow();
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            pipelineExecutorService.shutdownNow();
        }
    }
}
